<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" 
        :editor="editorRef" 
        :defaultConfig="toolbarConfig" 
        :mode="mode" />

        <Editor style="height: 500px; overflow-y: hidden;" 
        v-model="valueHtml" 
        @onChange="contentChange"
        :defaultConfig="editorConfig" 
        :mode="mode"
            @onCreated="handleCreated" />
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import fileApi from '@/api/file'
import msgUtil from '@/utils/msgUtil'

const editorRef = shallowRef()

const emits = defineEmits(['update:valueHtml'])

const props = defineProps({
    valueHtml : '',
    mode : {
        type :String,
        default : 'default'
    }
})

const valueHtml = ref(props.valueHtml)

// 内容 HTML
// const valueHtml = ref('')

// 模拟 ajax 异步获取内容
// onMounted(() => {
    
// })

const toolbarConfig = {}
const editorConfig = { 
    placeholder: '请输入内容...' ,
    
    MENU_CONF:{
        /**
         * @see https://www.wangeditor.com/v5/menu-config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
         */
        uploadImage : {
            server: fileApi.uploadOneURL,
            fieldName : 'file',
            maxFileSize : 10 * 1024 * 1024,
            customInsert(res, insertFn) {                  // JS 语法
                // res 即服务端的返回结果
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(res.data.url, res.data.org_file_name, res.data.url)
            },
        },

        uploadVideo:{
            server: fileApi.uploadOneURL,
            fieldName : 'file',
            maxFileSize : 1024 * 1024 * 1024,
            customInsert(res, insertFn) {                  // JS 语法
                // res 即服务端的返回结果
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(res.data.url, res.data.org_file_name, res.data.url)
            },
        }
    }
}

function contentChange(edit){
    // 更新model
    console.log('edit change', edit.getHtml())
    emits('update:valueHtml', edit.getHtml())
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return;
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

</script>